#include <iostream>

#include "gfx.h"

/* Audio! */
struct
{
	SDL_AudioSpec spec;
	Uint8   *sound;    /* Zeiger auf die Audiodaten */
	Uint32   soundlen; /* Länge der Audiodaten */
	int      soundpos; /* Aktuelle Abspielposition */
} wave;

void fillerup(void *unused, Uint8 *stream, int len)
{
	Uint8 *waveptr;
	int waveleft;

	waveptr = wave.sound + wave.soundpos;
	waveleft = wave.soundlen - wave.soundpos;

	while ( waveleft <= len )
	 {
		SDL_PauseAudio(1);
    		stream += waveleft;
    		len -= waveleft;
    		waveptr = wave.sound;
    		waveleft = wave.soundlen;
    		wave.soundpos = 0;
  	}

	SDL_MixAudio(stream, waveptr, len, SDL_MIX_MAXVOLUME);
  	wave.soundpos += len;
}

void polaris::window::refresh()
{
     //cout << "do refresh\n";
     SDL_Flip(screen);
}

void polaris::window::clear()
{
     SDL_FillRect(screen,NULL,0x000000);
}


int polaris::window::pollInputs()
{

     while (SDL_PollEvent (&event))
     {
	    int axisvalueUpDown;
	    int axisvalueLeftRight;

            switch (event.type)
            {
            case SDL_KEYDOWN:
                if(event.key.keysym.sym==SDLK_LEFT) {  playerControls.cursorleft = true; }
                if(event.key.keysym.sym==SDLK_RIGHT) {  playerControls.cursorright =true; }
                if(event.key.keysym.sym==SDLK_UP) {  playerControls.cursorup = true; }
                if(event.key.keysym.sym==SDLK_DOWN) {  playerControls.cursordown =true; }

                if(event.key.keysym.sym==SDLK_a) { playerControls2.cursorleft = true; }
                if(event.key.keysym.sym==SDLK_d) { playerControls2.cursorright = true;  }
                if(event.key.keysym.sym==SDLK_w) { playerControls2.cursorup = true; }
                if(event.key.keysym.sym==SDLK_s) {  playerControls2.cursordown = true; }

                if(event.key.keysym.sym==SDLK_SPACE) lastinput = KSPACE;
                if(event.key.keysym.sym==SDLK_RETURN) lastinput = KRETURN;
                if(event.key.keysym.sym==SDLK_1) lastinput = KONE;
                if(event.key.keysym.sym==SDLK_2) lastinput = KTWO;

                if(event.key.keysym.sym==SDLK_ESCAPE) lastinput = QUIT;

                break;

            case SDL_KEYUP:
                lastinput = 0;
                if(event.key.keysym.sym==SDLK_LEFT) {  playerControls.cursorleft = false; }
                if(event.key.keysym.sym==SDLK_RIGHT) {  playerControls.cursorright =false; }
                if(event.key.keysym.sym==SDLK_UP) {  playerControls.cursorup = false; }
                if(event.key.keysym.sym==SDLK_DOWN) { playerControls.cursordown =false; }

                if(event.key.keysym.sym==SDLK_a) {  playerControls2.cursorleft = false; }
                if(event.key.keysym.sym==SDLK_d) {  playerControls2.cursorright =false; }
                if(event.key.keysym.sym==SDLK_w) {  playerControls2.cursorup = false; }
                if(event.key.keysym.sym==SDLK_s) { playerControls2.cursordown =false; }

                break;


            case SDL_JOYAXISMOTION:

                /* handle joystick input for p1 */
                //axisvalueUpDown = SDL_JoystickGetAxis(joystick1, 1);
                //axisvalueLeftRight = SDL_JoystickGetAxis(joystick1, 0);

                //cout << axisvalueUpDown << " " <<axisvalueLeftRight << endl;

                if(axisvalueUpDown<-1000) { playerControls.cursorup = true; }
                else { playerControls.cursorup = false; }

                if(axisvalueUpDown>1000) {  playerControls.cursordown = true; }
                else { playerControls.cursordown = false; }


                if(axisvalueLeftRight<-1000) { playerControls.cursorleft = true; }
                else { playerControls.cursorleft = false; }

                if(axisvalueLeftRight>1000) {  playerControls.cursorright = true; }
                else { playerControls.cursorright = false; }


                /* p2 */
                //axisvalueUpDown = SDL_JoystickGetAxis(joystick2, 1);
                //axisvalueLeftRight = SDL_JoystickGetAxis(joystick2, 0);

                //cout << axisvalueUpDown << " " <<axisvalueLeftRight << endl;

                if(axisvalueUpDown<-1000) { playerControls2.cursorup = true; }
                else { playerControls2.cursorup = false; }

                if(axisvalueUpDown>1000) {  playerControls2.cursordown = true; }
                else { playerControls2.cursordown = false; }


                if(axisvalueLeftRight<-1000) { playerControls2.cursorleft = true; }
                else { playerControls2.cursorleft = false; }

                if(axisvalueLeftRight>1000) {  playerControls2.cursorright = true; }
                else { playerControls2.cursorright = false; }

            break;


            case SDL_QUIT:
                lastinput =  QUIT;
            break;

            default:
                break;
            }
     }

     return lastinput;
}

polaris::window::window(int sizew, int sizeh, char* title)
{
     cout << "entering constructor\n";

     SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);

        playerControls.cursorleft = 0;
        playerControls.cursorright = 0;
        playerControls.cursorup = 0;
        playerControls.cursordown = 0;

        playerControls2.cursorleft = 0;
        playerControls2.cursorright = 0;
        playerControls2.cursorup = 0;
        playerControls2.cursordown = 0;

     screen = NULL;
     lastinput = 0;

     /* Initialize SDL */
    if (SDL_Init (SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_AUDIO ) < 0)
    {
        printf ("Couldn't initialize SDL: %s\n", SDL_GetError ());
        exit (1);
    }
    atexit (SDL_Quit);

   //SDL_JoystickOpen(0);
//	joystick1 = SDL_JoystickOpen(0);
  //  	joystick2 = SDL_JoystickOpen(1);

    screen = SDL_SetVideoMode (sizew, sizeh,32, SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_RLEACCEL/*| SDL_FULLSCREEN*/ | SDL_HWACCEL);
    if (screen == NULL)
    {
        printf ("Couldn't set video mode: %s\n",
          SDL_GetError ());
        exit (2);
    }
    SDL_WM_SetCaption (title, NULL);

}


bool polaris::window::setImg(SDL_Surface *pic, int x, int y)
{
    SDL_Rect dest;
    dest.x = x;
    dest.y = y;
    dest.w = pic->w;
    dest.h = pic->h;

    SDL_BlitSurface(pic, NULL, screen, &dest);
    //SDL_UpdateRects(screen,1,&dest);

    return true;
}

bool polaris::window::setImg(polaris::player *p)
{
    setImg(p->gfx, (int)p->posX, (int)p->posY);

    return true;
}



void polaris::window::DrawPixel(int x, int y,Uint8 R, Uint8 G,Uint8 B)
{
    Uint32 color = SDL_MapRGB(screen->format, R, G, B);

  /*  if ( SDL_MUSTLOCK(screen) )
    {
        if ( SDL_LockSurface(screen) < 0 ) {
            return;
        }
    }*/

    switch (screen->format->BytesPerPixel) {
        case 1: { /* vermutlich 8 Bit */
            Uint8 *bufp;

            bufp = (Uint8 *)screen->pixels + y*screen->pitch + x;
            *bufp = color;
        }
        break;

        case 2: { /* vermutlich 15 Bit oder 16 Bit */
            Uint16 *bufp;

            bufp = (Uint16 *)screen->pixels + y*screen->pitch/2 + x;
            *bufp = color;
        }
        break;

        case 3: { /* langsamer 24-Bit-Modus, selten verwendet */
            Uint8 *bufp;

            bufp = (Uint8 *)screen->pixels + y*screen->pitch + x * 3;
            if(SDL_BYTEORDER == SDL_LIL_ENDIAN) {
                bufp[0] = color;
                bufp[1] = color >> 8;
                bufp[2] = color >> 16;
            } else {
                bufp[2] = color;
                bufp[1] = color >> 8;
                bufp[0] = color >> 16;
            }
        }
        break;

        case 4: { /* vermutlich 32 Bit */
            Uint32 *bufp;

            bufp = (Uint32 *)screen->pixels + y*screen->pitch/4 + x;
            *bufp = color;
        }
        break;
    }

   /* if ( SDL_MUSTLOCK(screen) )
    {
        SDL_UnlockSurface(screen);
    }*/
}



void polaris::window::loadsound(char* filename)
{
	SDL_LoadWAV(filename, &wave.spec,
            &wave.sound, &wave.soundlen);

	wave.spec.callback=fillerup;

	if( SDL_OpenAudio(&wave.spec, NULL) < 0 )
	{
        	fprintf(stderr,  "Kann Audio nicht ausgeben: %s\n",
                SDL_GetError());
	}
}

void polaris::window::playsound()
{
	SDL_PauseAudio(0);
}
